package com.swust.reactredis.pubsub;

import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReactiveSubscription;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @author: Chen Yixing
 * @since: 2024/5/2 09:16:54
 * @description:
 */
@Component
public class PubSubUsage<T> {
    @Autowired
    private ReactiveRedisTemplate<String, T> reactiveRedisTemplate;

    /**
     * 订阅
     */
    public Flux<T> listenTo(String topic) {
        Consumer<? super Throwable> consumer = msg -> System.out.println(msg);
        return reactiveRedisTemplate
                .listenTo(ChannelTopic.of(topic))
                .map(ReactiveSubscription.Message::getMessage)
                .doOnError(consumer);
    }

    /**
     * 发布
     */
    public Mono<Integer> publish(String topic, Publisher<? extends T> publisher) {
        return Flux.from(publisher)
                .flatMap(data -> reactiveRedisTemplate.convertAndSend(topic, data))
                .last(1L)
                .map(Number::intValue);
    }

//    public <T> void convertAndSend(String topic, T message) {
//        reactiveRedisTemplate.convertAndSend(topic, message);
//    }
}
